home *** CD-ROM | disk | FTP | other *** search
/ The Very Best of Atari Inside / The Very Best of Atari Inside 1.iso / mint / mntlb20 / lib / textio.c < prev    next >
C/C++ Source or Header  |  1992-03-10  |  1KB  |  73 lines

  1. /*
  2.  * textio: read/write routines for text. These can be used in programs
  3.  * where read and write are used instead of the (preferred) stdio routines
  4.  * for manipulating text files, by doing something like
  5.  *  #define read _text_read
  6.  * Written by Eric R. Smith and placed in the public domain.
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <unistd.h>
  11.  
  12. int
  13. _text_read(fd, buf, nbytes)
  14.     int fd;
  15.     char *buf;
  16.     int nbytes;
  17. {
  18.     char *to, *from;
  19.     int  r;
  20.  
  21. _again:
  22.     r = read(fd, buf, nbytes);
  23.     if (r <= 0)
  24.         return r;
  25.     nbytes = r;
  26.     to = from = buf;
  27.     while (r-- > 0) {
  28.         if (*from == '\r') {
  29.             from++; nbytes--;
  30.         }
  31.         else
  32.             *to++ = *from++;
  33.     }
  34.     if (nbytes == 0)
  35.         goto _again;
  36.     return nbytes;
  37. }
  38.  
  39. int
  40. _text_write(fd, from, nbytes)
  41.     int fd;
  42.     char *from;
  43.     int nbytes;
  44. {
  45. #ifdef __SOZOBON__
  46.     char buf[1024+2];
  47. #else
  48.     char buf[BUFSIZ+2];
  49. #endif
  50.     char *to, c;
  51.     int  w, r, bytes_written;
  52.  
  53.     bytes_written = 0;
  54.     while (bytes_written < nbytes) {
  55.         w = 0;
  56.         to = buf;
  57.         while (w < BUFSIZ && bytes_written < nbytes) {
  58.             if ((c = *from++) == '\n') {
  59.                 *to++ = '\r'; *to++ = c;
  60.                 w += 2;
  61.             }
  62.             else {
  63.                 *to++ = c;
  64.                 w++;
  65.             }
  66.             bytes_written++;
  67.         }
  68.         if ((r = write(fd, buf, w)) != w)
  69.             return (r < 0) ? r : bytes_written - (w-r);
  70.     }
  71.     return bytes_written;
  72. }
  73.